use crate::helpers::{count_ttr, /*count_unread_posts,*/ create_ttr, wrap_url /*Bot*/};
use anyhow::Result;
use db::Db;
use log::info;
use matrix_sdk::ruma::events::room::message::RoomMessageEventContent;
use matrix_sdk::{room::Room, ruma::events::room::message::OriginalSyncRoomMessageEvent, Client};

pub async fn random(
    ev: OriginalSyncRoomMessageEvent,
    _text: String,
    room: Room,
    _client: Client,
    db: Db,
) -> Result<()> {
    info!("finding random post");
    let user_id = ev.sender.to_string();
    // let user_id = db::models::MatrixOrTelegramId::MatrixId(&matrix_id);
    // let user_id = db.get_user_id(matrix_id,).await.unwrap();
    // let user_post = db.get_random_userpost(user_id).await?.unwrap();
    let post = db.get_random_post_matrix(&user_id).await?.unwrap();
    let mut answer = {
        let url_str = &post.original_url;
        if let Some(title) = post.title {
            wrap_url(url_str, &title)
        } else {
            url_str.to_string()
        }
    };
    let ttr = count_ttr(post.word_count);
    if let Some(ttr) = ttr {
        create_ttr(&mut answer, ttr)
    };

    let content = RoomMessageEventContent::text_markdown(answer);

    info!("sending random post");
    let response = room.send(content).await.unwrap();
    let event_id = response.event_id.to_string();
    db.create_message_event(post.id, event_id).await.unwrap();
    info!("sent");
    Ok(())
}
// impl PostRandom{
//      fn title(&self) -> Option<String>{
//          self.title.map(|title|title.to_string())
//      }
//  }*/
// fn original_or_real(user: &UserRandom, post: &UserPostRandom) -> bool {
//     user.show_real_url || post.show_real_url
// }
